<template>
  <van-button
    :icon="value === 1 ? 'good-job' : 'good-job-o'"
    :class="{
      liked: value === 1, //value为true 类名生效 反则不生效
    }"
    @click="onLike"
    :loading="loading"
  >
  </van-button>
</template>

<script>
import { addLike, deleteLike } from '@/api/article'
export default {
  name: 'LikeArticle',
  props: {
    value: {
      type: Number,
      required: true,
    },
    articleId: {
      type: [String, Number],
      required: true,
    },
  },
  data() {
    return {
      loading: false, //关注按钮的加载状态
    }
  },

  mounted() {},

  methods: {
    async onLike() {
      this.loading = true
      try {
        let status = -1
        if (this.value === 1) {
          //已经点赞 取消点赞
          await deleteLike(this.articleId)
        } else {
          //未点赞 添加点赞
          await addLike(this.articleId)
          status = 1
        }
        //更新视图 及收藏状态 props中数据不能更改 需传到父组件
        this.$emit('input', status) //更新视图 传到父组件数据才能改变
        this.$toast.success(status === 1 ? '点赞成功' : '取消点赞')
      } catch (err) {
        this.$toast.fail('操作失败，请重试')
      }
      this.loading = false
    },
  },
}
</script>

<style lang="less" scoped>
.liked {
  .van-icon {
    color: red;
  }
}
</style>
